from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.models.work_order import WorkOrder
from app.models.process_record import ProcessRecord
from app.models import db
from .work_orders_utils import get_current_user, apply_user_filter
from app.utils.auth import require_permission
from datetime import datetime, timedelta
from sqlalchemy import func, extract

work_orders_analytics_bp = Blueprint('work_orders_analytics', __name__)

@work_orders_analytics_bp.route('/stats', methods=['GET'])
@jwt_required()
@require_permission('work_order.view', 'work_order.view_all')
def get_work_order_stats():
    """获取工单统计数据"""
    try:
        current_user = get_current_user()
        query = WorkOrder.query

        # 根据用户角色过滤数据
        query = apply_user_filter(query, current_user)

        # 统计各状态的工单数量
        total = query.count()
        pending = query.filter_by(status='pending').count()
        assigned = query.filter_by(status='assigned').count()
        in_progress = query.filter_by(status='in_progress').count()
        completed = query.filter_by(status='completed').count()
        cancelled = query.filter_by(status='cancelled').count()
        
        # 统计各优先级的工单数量
        urgent = query.filter_by(priority='urgent').count()
        high = query.filter_by(priority='high').count()
        medium = query.filter_by(priority='medium').count()
        low = query.filter_by(priority='low').count()
        
        # 计算完成率
        completion_rate = round((completed / total * 100) if total > 0 else 0, 1)
        
        # 今日新增工单
        today = datetime.now().date()
        today_start = datetime.combine(today, datetime.min.time())
        today_end = datetime.combine(today, datetime.max.time())
        today_new = query.filter(
            WorkOrder.created_at >= today_start,
            WorkOrder.created_at <= today_end
        ).count()
        
        # 本周新增工单
        week_start = today - timedelta(days=today.weekday())
        week_start_dt = datetime.combine(week_start, datetime.min.time())
        week_new = query.filter(WorkOrder.created_at >= week_start_dt).count()
        
        # 逾期工单（已过期但未完成）
        overdue = query.filter(
            WorkOrder.due_date < datetime.now(),
            WorkOrder.status.notin_(['completed', 'cancelled'])
        ).count()

        return jsonify({
            'total': total,
            'status_stats': {
                'pending': pending,
                'assigned': assigned,
                'in_progress': in_progress,
                'completed': completed,
                'cancelled': cancelled
            },
            'priority_stats': {
                'urgent': urgent,
                'high': high,
                'medium': medium,
                'low': low
            },
            'completion_rate': completion_rate,
            'today_new': today_new,
            'week_new': week_new,
            'overdue': overdue
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_analytics_bp.route('/reports', methods=['GET'])
@jwt_required()
@require_permission('work_order.view', 'work_order.view_all')
def get_work_order_reports():
    """获取工单报表数据"""
    try:
        current_user = get_current_user()
        
        # 获取查询参数
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        dimension = request.args.get('dimension', 'day')  # day, week, month
        report_type = request.args.get('type', 'overview')  # overview, trend, performance
        
        # 设置默认时间范围（最近30天）
        if not start_date:
            start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
        if not end_date:
            end_date = datetime.now().strftime('%Y-%m-%d')
            
        # 转换为datetime对象
        start_dt = datetime.strptime(start_date, '%Y-%m-%d')
        end_dt = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
        
        # 基础查询
        query = WorkOrder.query.filter(
            WorkOrder.created_at >= start_dt,
            WorkOrder.created_at < end_dt
        )
        
        # 根据用户角色过滤数据
        query = apply_user_filter(query, current_user)
        
        if report_type == 'overview':
            return _get_overview_report(query, start_dt, end_dt)
        elif report_type == 'trend':
            return _get_trend_report(query, start_dt, end_dt, dimension)
        elif report_type == 'performance':
            return _get_performance_report(query, start_dt, end_dt)
        else:
            return jsonify({'error': '无效的报表类型'}), 400
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def _get_overview_report(query, start_dt, end_dt):
    """获取概览报表"""
    # 统计概览数据
    total_orders = query.count()
    completed_orders = query.filter_by(status='completed').count()
    pending_orders = query.filter_by(status='pending').count()
    processing_orders = query.filter(
        WorkOrder.status.in_(['assigned', 'in_progress'])
    ).count()
    cancelled_orders = query.filter_by(status='cancelled').count()
    
    completion_rate = round((completed_orders / total_orders * 100) if total_orders > 0 else 0, 1)
    
    # 状态分布统计
    status_stats = {
        'pending': pending_orders,
        'assigned': query.filter_by(status='assigned').count(),
        'in_progress': query.filter_by(status='in_progress').count(),
        'completed': completed_orders,
        'cancelled': cancelled_orders
    }
    
    # 优先级分布统计
    priority_stats = {
        'low': query.filter_by(priority='low').count(),
        'medium': query.filter_by(priority='medium').count(),
        'high': query.filter_by(priority='high').count(),
        'urgent': query.filter_by(priority='urgent').count()
    }
    
    # 按创建者统计
    creator_stats = db.session.query(
        WorkOrder.creator_id,
        func.count(WorkOrder.id).label('count')
    ).filter(
        WorkOrder.created_at >= start_dt,
        WorkOrder.created_at < end_dt
    ).group_by(WorkOrder.creator_id).all()
    
    # 按分配者统计
    assignee_stats = db.session.query(
        WorkOrder.assignee_id,
        func.count(WorkOrder.id).label('count')
    ).filter(
        WorkOrder.created_at >= start_dt,
        WorkOrder.created_at < end_dt,
        WorkOrder.assignee_id.isnot(None)
    ).group_by(WorkOrder.assignee_id).all()
    
    return jsonify({
        'overview': {
            'total': total_orders,
            'completed': completed_orders,
            'pending': pending_orders,
            'processing': processing_orders,
            'cancelled': cancelled_orders,
            'completion_rate': completion_rate
        },
        'status_distribution': status_stats,
        'priority_distribution': priority_stats,
        'creator_stats': [{'creator_id': stat[0], 'count': stat[1]} for stat in creator_stats],
        'assignee_stats': [{'assignee_id': stat[0], 'count': stat[1]} for stat in assignee_stats]
    }), 200

def _get_trend_report(query, start_dt, end_dt, dimension):
    """获取趋势报表"""
    trend_data = []
    
    if dimension == 'day':
        # 按天统计
        current_date = start_dt
        while current_date < end_dt:
            next_date = current_date + timedelta(days=1)
            day_query = query.filter(
                WorkOrder.created_at >= current_date,
                WorkOrder.created_at < next_date
            )
            
            day_total = day_query.count()
            day_completed = day_query.filter_by(status='completed').count()
            day_pending = day_query.filter_by(status='pending').count()
            day_processing = day_query.filter(
                WorkOrder.status.in_(['assigned', 'in_progress'])
            ).count()
            day_cancelled = day_query.filter_by(status='cancelled').count()
            
            day_completion_rate = round((day_completed / day_total * 100) if day_total > 0 else 0, 1)
            
            trend_data.append({
                'date': current_date.strftime('%Y-%m-%d'),
                'total': day_total,
                'pending': day_pending,
                'processing': day_processing,
                'completed': day_completed,
                'cancelled': day_cancelled,
                'completion_rate': day_completion_rate
            })
            
            current_date = next_date
    
    elif dimension == 'week':
        # 按周统计
        current_date = start_dt - timedelta(days=start_dt.weekday())
        while current_date < end_dt:
            next_date = current_date + timedelta(days=7)
            week_query = query.filter(
                WorkOrder.created_at >= current_date,
                WorkOrder.created_at < next_date
            )
            
            week_total = week_query.count()
            week_completed = week_query.filter_by(status='completed').count()
            week_completion_rate = round((week_completed / week_total * 100) if week_total > 0 else 0, 1)
            
            trend_data.append({
                'date': current_date.strftime('%Y-%m-%d'),
                'total': week_total,
                'completed': week_completed,
                'completion_rate': week_completion_rate
            })
            
            current_date = next_date
    
    elif dimension == 'month':
        # 按月统计
        current_date = start_dt.replace(day=1)
        while current_date < end_dt:
            if current_date.month == 12:
                next_date = current_date.replace(year=current_date.year + 1, month=1)
            else:
                next_date = current_date.replace(month=current_date.month + 1)
            
            month_query = query.filter(
                WorkOrder.created_at >= current_date,
                WorkOrder.created_at < next_date
            )
            
            month_total = month_query.count()
            month_completed = month_query.filter_by(status='completed').count()
            month_completion_rate = round((month_completed / month_total * 100) if month_total > 0 else 0, 1)
            
            trend_data.append({
                'date': current_date.strftime('%Y-%m'),
                'total': month_total,
                'completed': month_completed,
                'completion_rate': month_completion_rate
            })
            
            current_date = next_date
    
    return jsonify({
        'trend_data': trend_data,
        'dimension': dimension
    }), 200

def _get_performance_report(query, start_dt, end_dt):
    """获取性能报表"""
    # 平均处理时间统计
    completed_orders = query.filter_by(status='completed').all()
    
    total_duration = 0
    duration_count = 0
    
    for order in completed_orders:
        if order.updated_at and order.created_at:
            duration = (order.updated_at - order.created_at).total_seconds() / 3600  # 转换为小时
            total_duration += duration
            duration_count += 1
    
    avg_duration = round(total_duration / duration_count, 2) if duration_count > 0 else 0
    
    # 逾期工单统计
    overdue_orders = query.filter(
        WorkOrder.due_date < datetime.now(),
        WorkOrder.status.notin_(['completed', 'cancelled'])
    ).count()
    
    # 按优先级的完成情况
    priority_performance = {}
    for priority in ['low', 'medium', 'high', 'urgent']:
        priority_query = query.filter_by(priority=priority)
        priority_total = priority_query.count()
        priority_completed = priority_query.filter_by(status='completed').count()
        priority_rate = round((priority_completed / priority_total * 100) if priority_total > 0 else 0, 1)
        
        priority_performance[priority] = {
            'total': priority_total,
            'completed': priority_completed,
            'completion_rate': priority_rate
        }
    
    # 工作量分布（按分配者）
    workload_stats = db.session.query(
        WorkOrder.assignee_id,
        func.count(WorkOrder.id).label('total'),
        func.sum(func.case([(WorkOrder.status == 'completed', 1)], else_=0)).label('completed')
    ).filter(
        WorkOrder.created_at >= start_dt,
        WorkOrder.created_at < end_dt,
        WorkOrder.assignee_id.isnot(None)
    ).group_by(WorkOrder.assignee_id).all()
    
    workload_data = []
    for stat in workload_stats:
        completion_rate = round((stat.completed / stat.total * 100) if stat.total > 0 else 0, 1)
        workload_data.append({
            'assignee_id': stat.assignee_id,
            'total': stat.total,
            'completed': stat.completed or 0,
            'completion_rate': completion_rate
        })
    
    return jsonify({
        'performance': {
            'avg_duration_hours': avg_duration,
            'overdue_count': overdue_orders,
            'priority_performance': priority_performance,
            'workload_distribution': workload_data
        }
    }), 200

@work_orders_analytics_bp.route('/dashboard', methods=['GET'])
@jwt_required()
@require_permission('dashboard.view')
def get_dashboard_data():
    """获取仪表板数据"""
    try:
        current_user = get_current_user()
        
        # 获取基础统计
        query = WorkOrder.query
        query = apply_user_filter(query, current_user)
        
        # 今日数据
        today = datetime.now().date()
        today_start = datetime.combine(today, datetime.min.time())
        today_end = datetime.combine(today, datetime.max.time())
        
        today_query = query.filter(
            WorkOrder.created_at >= today_start,
            WorkOrder.created_at <= today_end
        )
        
        # 本周数据
        week_start = today - timedelta(days=today.weekday())
        week_start_dt = datetime.combine(week_start, datetime.min.time())
        week_query = query.filter(WorkOrder.created_at >= week_start_dt)
        
        # 我的工单（仅对普通用户）
        my_orders = {}
        if current_user.role == 'user':
            my_assigned = query.filter_by(assignee_id=current_user.id).count()
            my_created = query.filter_by(creator_id=current_user.id).count()
            my_pending = query.filter(
                WorkOrder.assignee_id == current_user.id,
                WorkOrder.status.in_(['pending', 'assigned'])
            ).count()
            
            my_orders = {
                'assigned_to_me': my_assigned,
                'created_by_me': my_created,
                'pending_tasks': my_pending
            }
        
        dashboard_data = {
            'today': {
                'new_orders': today_query.count(),
                'completed': today_query.filter_by(status='completed').count(),
                'pending': today_query.filter_by(status='pending').count()
            },
            'week': {
                'new_orders': week_query.count(),
                'completed': week_query.filter_by(status='completed').count(),
                'in_progress': week_query.filter_by(status='in_progress').count()
            },
            'total': {
                'all_orders': query.count(),
                'urgent_orders': query.filter_by(priority='urgent').count(),
                'overdue_orders': query.filter(
                    WorkOrder.due_date < datetime.now(),
                    WorkOrder.status.notin_(['completed', 'cancelled'])
                ).count()
            }
        }
        
        if my_orders:
            dashboard_data['my_orders'] = my_orders
        
        return jsonify(dashboard_data), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500